package com.chenfy.everysound.net

import android.util.Log
import com.chenfy.everysound.base.App
import com.chenfy.everysound.entity.SoundItem
import kotlinx.coroutines.*
import java.io.File

object DownloadManager {
    private const val TAG = "DownloadManager"
    private val itemList = mutableListOf<SoundItem>()
    private val listeners = mutableListOf<(id:String) -> Unit>()
    private val soundService: ISoundService by lazy {
        ServiceCreator.create()
    }

    suspend fun download(item: SoundItem) {
        if (item in itemList) {
            return
        }
        withContext(Dispatchers.IO) {
            itemList.add(item)
            val resultList = item.sound.map { url ->
                async(Dispatchers.IO) {
                    Log.d(TAG, "开始下载:${item.name}")
                    val resp = soundService.downloadSound(url)
                    val context = App.context
                    val fileDir = context.filesDir
                    val soundFile = File(fileDir, url)
                    val parent = soundFile.parentFile
                    parent?.let {
                        if (!it.exists()) {
                            it.mkdirs()
                        }
                    }
                    soundFile.createNewFile()
                    resp.byteStream().use {
                        it.copyTo(soundFile.outputStream())
                    }
                    resp.close()
                    Log.d(TAG, "下载完成:${item.name}")
                    true
                }
            }
            resultList.forEach {
                it.await()
            }
            itemList.remove(item)
        }
    }

}